<template>
  <div class="executor-main">
    <el-container direction="vertical">
      <el-container class="execute" direction="vertical">
        <el-main clas="args">
          <h2>“App {{ this.appId }}” 应用启动</h2>
          <!-- <json-edit v-for="(item, key) in nowTaskArgs" :ref="'args' + key" :key="'args' + key" :arg_key="key"
            :sub_task_arg="item" :memory_bus="memoryBus" @fill_argument="fillArgument" /> -->
          <!-- <div v-if="Object.keys(userInput).length > 0" class="data-to-send">
            <h3>用户输入:</h3>
            <div v-for="(value, key) in userInput" :key="key">
              {{ key }}: {{ value }}
            </div>
          </div> -->
          <div v-if="allUserInputs.length > 0">
            <div v-for="(userInput, index) in allUserInputs" :key="index">
              <h4>执行Task {{ index + 1 }}： {{ userInput.tool_name }}</h4>
              <template v-if="Object.keys(userInput).length > 1">
                <!-- Check if there are fields other than 'tool_name' -->
                <h4>用户输入:</h4>
                <div v-for="(value, key) in userInput" :key="key" v-if="key !== 'tool_name'">
                  {{ key }}: {{ value }}
                </div>
              </template>
            </div>
          </div>
        </el-main>
        <!-- <el-main class="output">
          <output-edit />
          <div v-if="!isRun" class="buttons">
            <el-row type="flex" align="middle" :gutter="6">
              <el-col :span="4">
                <el-button type="primary" plain @click="runTask"> {{ runButtonMessage }} </el-button>
              </el-col>
              <el-col :span="6">
                <el-button plain @click="llmGenerate">大模型匹配参数</el-button>
              </el-col>
              <el-col :span="4">
                <el-link target="_blank" @click="getMemoryBus"> 查看 Memory Bus </el-link>
              </el-col>
            </el-row>
          </div>
        </el-main> -->
      </el-container>
      <el-main>
        <template v-if="executeLogs.length > 0">
          <h2>执行结果</h2>
          <div v-for="(item, key) in executeLogs" :key="'logs' + key">
            <h4>Task {{ key + 1 }}</h4>
            <!-- <p>message: {{ item.message }}</p> -->
            <json-viewer :value="item" />
          </div>
        </template>
      </el-main>
    </el-container>
    <!-- 弹出MemoryBus的部分 -->
    <el-dialog :visible.sync="dialogVisible" title="Memory Bus 的内容如下:">
      <json-viewer :value="memoryBus" />
    </el-dialog>
    <!-- 弹出input输入框 -->
    <el-dialog :visible.sync="inputDialogVisible" :title="`执行Task${nowTaskContent.task_id}：${nowTaskContent.tool_name}`">
      <el-form>
        <div v-for="(arg, index) in args" :key="index">
          <div v-if="arg.source === 'input'">
            <el-form-item :label="arg.input.description">
              <el-input v-model="arg.value"
                :type="getInputType(arg.input.type)"></el-input>
            </el-form-item>
          </div>
        </div>
        <el-form-item>
          <el-button type="primary" @click="submitForm" class="center">提交</el-button>
          <!-- <el-button @click="inputDialogVisible = false">取消</el-button> -->
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 重新执行的弹窗相关
    <el-dialog :visible.sync="rerunVisible" title="执行结束，是否重新执行">
      <span slot="footer" class="dialog-footer">
        <el-button @click="rerunConfirm">取消</el-button>
        <el-button type="primary" @click="rerunConfirm">确认</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import { getAppDetail, executeAppStep, getExecutroMemoryBus } from '@/api/executor'
// import { getMemoryBus } from '@/api/workflow'
import jsonEdit from '@/components/AppCreate/task/jsonEdit.vue'
import outputEdit from '@/components/AppCreate/output/outputEdit.vue'

export default {
  components: { jsonEdit, outputEdit },
  props: {
    appId: {
      type: Number,
      required: true,
      default: -1
    }
  },
  data() {
    return {
      /* 保存的整个应用详情 */
      appDetail: {},
      /* 解析参数相关 */
      nowOnTask: 0,
      nowTaskContent: {},
      nowTaskArgs: [],
      args: [],
      memoryBus: {},
      /* 运行与输出结果相关 */
      executeLogs: [],
      userInput: {},
      allUserInputs: [],
      execution_count: 0, // 初始化 execution_count
      isRun: false,
      /* 对话框相关 */
      dialogVisible: false,
      inputDialogVisible: false
      /* 执行结束重新执行相关 */
      // rerunVisible: false
    }
  },
  computed: {
    notRunToEnd() {
      return this.nowOnTask < this.appDetail.task_list.length
    },
    runButtonMessage() {
      return (this.notRunToEnd ? '执行' : '重新执行')
    }
  },
  created() {
    this.getDetailAndShow()
    /* this.executeLogs.push({
      'code': 0,
      'data': {
        'createTime': 0,
        'description': 'string',
        'formatType': 'string',
        'hostUuid': 'string',
        'id': 0,
        'name': 'string',
        'providerLocation': 'string',
        'size': 0,
        'status': 'string',
        'usageType': 'string',
        'uuid': 'string'
      },
      'message': 'string'
    })*/
  },
  methods: {
    // 根据appID获取app_detail
    getDetailAndShow() {
      getAppDetail(this.appId).then(res => {
        console.log('获取到的应用详情:', res)
        // 保存应用详情
        this.appDetail = res
        // 同步执行到哪一步
        this.autoFillArgs(this.execution_count)
      }).catch(error => {
        console.log('执行时获取详情出错:', error)
      })
    },
    // 解析远端发来的detail,将能填的值都填好
    autoFillArgs(task) {
      /** * 首先，清空现在的任务信息，并切换到下一个task * **/
      this.nowOnTask = task
      this.nowTaskContent = this.appDetail.task_list.at(task)
      // console.log(this.nowTaskContent, this.taskList)
      this.nowTaskArgs = []
      this.args = this.nowTaskContent.args
      //console.log(this.args)

      /** * 然后，根据MemoryBus解析args * **/
      const autoChoose = []
      const args = this.nowTaskContent.args
      for (const key in args) {
        const o_arg = args[key]
        const arg = {
          'name': o_arg.name,
          'description': o_arg.description,
          'type': o_arg.type,
          'value': ''
        }
        this.nowTaskArgs.push(arg)
        autoChoose.push({
          'source': o_arg.source,
          'value': o_arg.value
        })
      }
      /** * 其次，获取MemoryBus * **/
      getExecutroMemoryBus().then((res) => {
        this.memoryBus = res
        /** * 最后，调用子组件参数让它们自己填入数据 * **/
        // this.$nextTick(function () {
        //   for (const key in args) {
        //     this.$refs['args' + key][0].autoChooseValue(autoChoose[key])
        //   }
        // })
      }).catch(error => {
        console.log('子组件填参', error)
      })
      // 检查是否有args的source是'input'
      const hasInputArgs = this.args.some(arg => arg.source === 'input');

      // 如果有，则显示输入框
      if (hasInputArgs) {
        this.inputDialogVisible = true;
      } else {
        // 如果没有需要用户输入的字段，自动执行下一步
        this.submitForm();
      }
    },
    // 选择值来填充
    fillArgument(id, value) {
      //console.log(id, value)
      // 将数据填入arg
      // this.sub_task_args[id][key] = value
      // 固定将数据填入arg的value字段
      this.nowTaskArgs[id]['value'] = value
      // console.log('arg', this.nowTaskArgs)
    },
    runTask() {
      if (this.notRunToEnd) {
        // 正常的执行
        /** 从jsonEdit组件里获取填好的value */
        const info = []
        for (const key in this.nowTaskArgs) {
          info.push(this.$refs['args' + key][0].getExecutableArg())
        }
        //console.log('获取的info：', info)
        /** 覆盖整个应用详情对应的args值 */
        this.appDetail.task_list.at(this.nowOnTask).args = info
        //console.log('覆盖后的appDetail', this.appDetail)
        /** 发送并执行 */
        executeAppStep(this.appDetail).then(response => {
          //console.log('单步执行task：', response)
          this.executeLogs.push(response)
          // 切换到下一个task
          this.nowOnTask = this.nowOnTask + 1
          console.log('切换到下一个task:', this.nowOnTask)
          if (this.notRunToEnd) {
            /** 执行成功后刷新task的信息 */
            this.autoFillArgs(this.nowOnTask)
          }/** else {
             执行到最后一个task,准备刷新
            // this.rerunVisible = true
          }*/
        }).catch(error => {
          console.log('执行单步task失败：', error)
        })
      } else {
        // 执行到末尾，重新执行
        // this.rerunVisible = false
        /** 发送并执行 */
        executeAppStep(this.appDetail).then(response => {
          console.log('最后的执行task：', response)
          /** 清空task */
          this.executeLogs = []
          this.getDetailAndShow()
          // this.autoFillArgs(0)
          // this.executeLogs.push(response)
        }).catch(error => {
          console.log('最后的执行失败：', error)
        })
      }
    },
    llmGenerate() {
      alert('开发中')
    },
    getMemoryBus() {
      this.dialogVisible = true
      getExecutroMemoryBus().then(res => {
        this.memoryBus = res
        //console.log('获取到的MemoryBus：', this.memoryBus)
      }).catch(error => {
        console.log('获取MemoryBus失败:', error)
      })
    },
    getInputType(type) {
      return type === "editbox" ? "text" : type;
    },
    async submitForm() {
      try {
        const res = await getExecutroMemoryBus();
        this.memoryBus = res;
        this.args.forEach(arg => {
          if (arg.source === 'refer') {
            const path = arg.value.split('.');
            console.log(path);
            let value = this.memoryBus;
            console.log(value);
            for (let i = 0; i < path.length; i++) {
              value = value[path[i]];
              if (value === undefined) break;
            }
            arg.value = value;
          }
        });

        const dataToSend = this.nowTaskContent.args.reduce((acc, arg) => {
          acc[arg.name] = arg.value;
          return acc;
        }, {});
        Object.keys(dataToSend).forEach(key => {
          const arg = this.args.find(arg => arg.name === key);
          if (arg) {
            arg.value = dataToSend[key];
          }
        });
        const userInput = this.args.reduce((acc, arg) => {
          if (arg.source === 'input') {
            acc[arg.input.name] = arg.value;
          }
          return acc;
        }, {});

        userInput.tool_name = this.nowTaskContent.tool_name;
        const argsWithoutInput = this.args.map(arg => {
          // Destructure the object to remove the 'input' property
          const { input, ...rest } = arg;
          return rest; // Return the object without 'input'
        });

        this.userInput = userInput;
        this.allUserInputs.push({ ...userInput })
        this.inputDialogVisible = false;
        this.appDetail.task_list.at(this.nowOnTask).args = argsWithoutInput;
        //console.log('WithoutInput覆盖后的appDetail', this.appDetail);

        /** 发送并执行 */
        executeAppStep(this.appDetail).then(response => {
          console.log('单步执行task：', response);
          this.executeLogs.push(response);
          // 切换到下一个task
          this.nowOnTask = this.nowOnTask + 1;
          console.log('切换到下一个task:', this.nowOnTask);
          if (this.notRunToEnd) {
            /** 执行成功后刷新task的信息 */
            this.autoFillArgs(this.nowOnTask);
          }
          /** else {
             执行到最后一个task,准备刷新
            // this.rerunVisible = true
          }*/
        }).catch(error => {
          console.log('执行单步task失败：', error);
        });
        this.execution_count += 1; // 增加 execution_count

      } catch (error) {
        console.log('获取MemoryBus失败:', error);
      }
    }
  }
}
</script>

<style scoped>
.execute {
  width: 70%;
}

.logs {
  width: 30%;
}

.buttons {
  margin-top: 20px;
}

.center {
  margin: 0 auto;
  display: block;
}
</style>
